package com.example.administrator.express.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.administrator.express.R;
import com.example.administrator.express.db.UserDao;
import com.example.administrator.express.http.HttpClient;
import com.example.administrator.express.http.HttpResponseHandler;
import com.example.administrator.express.model.Users;
import com.example.administrator.express.utils.SharedPreferences;
import com.google.gson.Gson;

import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.FormBody;
import okhttp3.Request;

public class Login extends Activity {

    @Bind(R.id.btnSure)
    Button btnSure;
    @Bind(R.id.btnClose)
    Button btnClose;
    @Bind(R.id.phone)
    EditText mUser;
    @Bind(R.id.code)
    EditText mPassword;
    ;

    Users users;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);


    }

    public void loginbyloginId(String loginId, String password) {

        if (loginId.equals(mUser.getText().toString()) && password.equals(mPassword.getText().toString())) {
            Intent intent = new Intent();
            intent.setClass(Login.this, MainActivity.class);
            startActivity(intent);
            //Toast.makeText(getApplicationContext(), "��¼�ɹ�", Toast.LENGTH_SHORT).show();
        } else if ("".equals(loginId) || "".equals(password)) {
            new AlertDialog.Builder(Login.this)

                    .setTitle("账号不存在")
                    .setMessage("΢此账户不存在")
                    .create().show();
        } else {

            new AlertDialog.Builder(Login.this)

                    .setTitle("登录失败")
                    .setMessage("΢请输入正确的账号与密码\n请检查后继续")
                    .create().show();
        }

        //��¼��ť
        /*
          Intent intent = new Intent();
		intent.setClass(Login.this,Whatsnew.class);
		startActivity(intent);
		Toast.makeText(getApplicationContext(), "��¼�ɹ�", Toast.LENGTH_SHORT).show();
		this.finish();*/
    }


    @OnClick({R.id.btnSure, R.id.btnClose})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnSure:
                login();

                break;
            case R.id.btnClose:
                this.finish();
                break;
        }
    }

    public void login() {
        try {
            String url = "http://oa24406206.carp.mopaasapp.com/";
            url = url + "login";
            FormBody formBody = new FormBody.Builder()
                    .add("password", mPassword.getText().toString())
                    .add("loginId", mUser.getText().toString())
                    .build();
            HttpClient.post(url, formBody, new HttpResponseHandler() {


                @Override
                public void onSuccess(int statusCode, String content) {
                    Gson gson = new Gson();
                    users = gson.fromJson(content, Users.class);
                    System.out.println("成功:" + content);


                    if (users == null) {
                        new AlertDialog.Builder(Login.this)
                                .setTitle("账号不存在")
                                .setMessage("此账户不存在")
                                .create().show();
                    } else {
                        saveTodb(users);
                        String loginId = String.valueOf(users.getLoginId());
                        String password = users.getPassword();
                        loginbyloginId(loginId, password);
                    }

                }

                @Override
                public void onFailure(Request request, IOException e) {
                    super.onFailure(request, e);
                    System.out.println("链接失败:");
                    new AlertDialog.Builder(Login.this)

                            .setTitle("登录失败")
                            .setMessage("΢访问失败")
                            .create().show();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveTodb(Users users) {
        SharedPreferences sharedPreferences = SharedPreferences.getInstance();
        sharedPreferences.putInt("loginId", users.getLoginId());
        UserDao userdao = new UserDao(getApplicationContext());
        Users localusers = userdao.getByLoginId(users.getLoginId());
        System.out.println(users);
        if (localusers == null) {
            userdao.add(users);
            System.out.println("已加入数据库：" + users);
        } else {
            userdao.update(users);
            System.out.println("已更新数据库：" + users);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            finish();
            System.exit(0);

        }
        return super.onKeyDown(keyCode, event);
    }
}
